package org.gitman.agent.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

import org.gitman.agent.platform.GraphEditor;
import org.gitman.agent.platform.PlatformManager;
import org.gitman.agent.platform.VertexID;

import com.mxgraph.model.mxCell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.view.mxGraph;

public class GraphDisplPanel extends JPanel {
	
	private PlatformManager platformManager;
	private GraphEditor graphEditor;
	public static int SIZE = 30;
	private mxGraph graph;
	private mxGraphComponent graphComponent;
	
	public GraphDisplPanel(PlatformManager platformManager){
		this.platformManager = platformManager;
		this.graphEditor = platformManager.getGraphEditor();
		graphEditor.setDisplay(this);
		
		setLayout(new BorderLayout());		
	}
	
	public mxGraphComponent getGraphComponent(){
		return graphComponent;
	}
	
	public void setGraphComponent(final mxGraphComponent graphComponent) {
		removeAll();
		add(graphComponent);
		this.graphComponent = graphComponent;
		graph = graphEditor.getGraph();
		graphComponent.getViewport().setBackground(Color.WHITE);
		graphComponent.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		graphComponent.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		graphComponent.getGraphControl().addMouseListener(new GraphMouseAdapter(this, platformManager));

		paintAll(getGraphics());
		
		
	}
	
	public Object insertVertex(int x, int y){
		Object v = null;
		graph.getModel().beginUpdate();
		try{
			String val = VertexID.next();
			v = graphEditor.getGraph().insertVertex(graph.getDefaultParent(), val, val,  x, y, SIZE, SIZE, "defaultVertex;" + mxConstants.STYLE_SHAPE + "=" +  mxConstants.SHAPE_ELLIPSE);
		}finally{
			graph.getModel().endUpdate();
		}
		return v;
	}
	
	public Object insertEdge(Object from, Object to){
		Object e = null;
		graph.getModel().beginUpdate();
		try{
			e = graphEditor.getGraph().insertEdge(graph.getDefaultParent(), null, "",  from, to);
		}finally{
			graph.getModel().endUpdate();
		}		
		return e;
	}
	
}
